﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;
using WebAPISelfHostDemo.Model;
using Xunit;

namespace WebAPITest
{
    /// <summary>
    /// 单元测试用例（Xunit）
    /// 注意：测试前需要先启动【WebAPISelfHostDemo】项目作为服务程序
    /// </summary>
    public class TestCase
    {
        private readonly HttpClient client = new HttpClient();

        public TestCase()
        {
            client.BaseAddress = new Uri("http://localhost:8080");
        }

        [Fact]
        public void ListAllProducts()
        {
            HttpResponseMessage resp = client.GetAsync("api/products").Result;
            resp.EnsureSuccessStatusCode();

            var products = resp.Content.ReadAsAsync<IEnumerable<Product>>().Result;
            foreach (var p in products)
            {
                Console.WriteLine("{0} {1} {2} ({3})", p.Id, p.Name, p.Price, p.Category);
            }
        }

        [Theory]
        [InlineData(1)]
        [InlineData(2)]
        [InlineData(3)]
        public Product ListProduct(int id)
        {
            var resp = client.GetAsync(string.Format("api/products/{0}", id)).Result;
            resp.EnsureSuccessStatusCode();

            var product = resp.Content.ReadAsAsync<Product>().Result;

            Console.WriteLine("{0} {1} {2} ({3})", product.Id, product.Name, product.Price, product.Category);

            return product;
        }

        [Theory]
        [InlineData("Toys")]
        public IEnumerable<Product> ListProducts(string category)
        {
            Console.WriteLine("Products in '{0}':", category);

            string query = string.Format("api/products?category={0}", category);

            var resp = client.GetAsync(query).Result;
            resp.EnsureSuccessStatusCode();

            var products = resp.Content.ReadAsAsync<IEnumerable<Product>>().Result;
            foreach (var p in products)
            {
                Console.WriteLine("{0} {1} {2} ({3})", p.Id, p.Name, p.Price, p.Category);
            }
            return products;
        }

        [Fact]
        public async Task<IEnumerable<Product>> ListAllProductsAsync()
        {
            HttpResponseMessage resp = await client.GetAsync("api/products");
            if (resp.IsSuccessStatusCode)
            {
                var products = await resp.Content.ReadAsAsync<IEnumerable<Product>>();

                return products;
            }
            return null;
        }
    }
}